package com.qfedu.lc.server.controller;


import cn.hutool.json.JSONUtil;
import com.qfedu.lc.common.config.RedisKeyConfig;
import com.qfedu.lc.common.param.UserAdd;
import com.qfedu.lc.common.param.UserLogin;
import com.qfedu.lc.common.vo.R;
import com.qfedu.lc.server.entity.User;
import com.qfedu.lc.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 1.用户表 前端控制器
 * </p>
 *
 * @author wgz
 * @since 2023-10-30
 */
@Slf4j
@RestController
@RequestMapping("/server/user")
public class UserController {

    @Autowired
    private UserService userService ;

    @Autowired
    private StringRedisTemplate template;

    @PostMapping("/registerUser")
    public R registerUser(@RequestBody UserAdd userAdd, HttpServletRequest request){

        // 所有的业务放到 server层
       return userService.registerUser(userAdd,request.getRemoteAddr());

    }

    @PostMapping("/loginpass")
    public R loginPass(@RequestBody UserLogin userLogin,HttpServletRequest request){

        return userService.loginPass(userLogin,request.getRemoteAddr());

    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public R logout(HttpServletRequest request){

        String token = request.getHeader("Lctoken");
        log.info("token:"+token);

        String key = RedisKeyConfig.LOGIN_TOKEN+token;
        if (template.hasKey(key)){

           // 将json字符串转化为实体类
            User user = JSONUtil.toBean(template.opsForValue().get(key), User.class);
            // 删除token
            template.delete(key);
            // 记录当前token在线的key 也需要删除  phone + token
            template.delete(RedisKeyConfig.LOGIN_UID_TOKEN+user.getPhone()+":"+token);

            return R.ok("退出登录成功");

        }else {
            return R.fail("该用户登录已经失效，需要重新登录");
        }

    }

}

